// ==UserScript==
// @name           DiddlySquat
// @namespace      Scrumdidilyumptio.us
// @description    DidilySquat GM Script - This script looks up any didilies from Scrumdidilyumptio.us for the current page.
// @include        *
// ==/UserScript==


// The drag functionality was unabashedly stollen from the RSS Panel script: 
// http://www.xs4all.nl/~jlpoutre/BoT/Javascript/RSSpanel
// Hopefully someday I'll be that cool, but I doubt it.

//GM_log('scrollHeight == ' + document.body.scrollHeight);
//GM_log('clientHeight == ' + document.body.clientHeight);
//(document.scrollHeight > document.clientHeight) ? GM_log('yes scrolling') : GM_log('no scrolling')

var domainList = ['gmail.com', 'mail.google.com', 'scrumdidilyumptio.us/didilies', 'scrumdidilyumptio.us/signin'];
var domainOK = true;
//GM_log('before loop; domainOK = ' + domainOK);
for (var i=0; i<domainList.length; i++)
{
	
	//GM_log('in loop[' + i +']; domainOK = ' + domainOK);
	//GM_log('domainList[' + i + '] = ' + domainList[i]);
	if(location.href.match(domainList[i]) != null)
	{
		//GM_log('match! == ' + domainList[i]);
		domainOK=false;
		break;
	}
}

//GM_log('after loop; domainOK = ' + domainOK);

if(domainOK)
{ // domain checks out, start the whole process
var Drag = function(){ this.init.apply( this, arguments ); };

Drag.fixE = function( e )
{
  if( typeof e == 'undefined' ) e = window.event;
  if( typeof e.layerX == 'undefined' ) e.layerX = e.offsetX;
  if( typeof e.layerY == 'undefined' ) e.layerY = e.offsetY;
  return e;
};

Drag.prototype.init = function( handle, dragdiv )
{
  this.div = dragdiv || handle;
  this.handle = handle;
  if( isNaN(parseInt(this.div.style.left)) ) this.div.style.left  = '0px';
  if( isNaN(parseInt(this.div.style.top)) ) this.div.style.top = '0px';
  this.onDragStart = function(){};
  this.onDragEnd = function(){};
  this.onDrag = function(){};
  this.onClick = function(){};
  this.mouseDown = addEventHandler(this.handle, 'mousedown', this.start, this);
};

Drag.prototype.start = function( e )
{
  // this.mouseUp = addEventHandler(this.handle, 'mouseup', this.end, this);
  e = Drag.fixE(e);

  this.started = new Date();
  var y = this.startY = parseInt(this.div.style.top);
  var x = this.startX = parseInt(this.div.style.left);
  this.onDragStart(x, y);
  this.lastMouseX = e.clientX;
  this.lastMouseY = e.clientY;
  this.documentMove = addEventHandler(document, 'mousemove', this.drag, this);
  this.documentStop = addEventHandler(document, 'mouseup', this.end, this);
  if (e.preventDefault) e.preventDefault();
  return false;
};

Drag.prototype.drag = function( e )
{
  e = Drag.fixE(e);
  var ey = e.clientY;
  var ex = e.clientX;
  var y = parseInt(this.div.style.top);
  var x = parseInt(this.div.style.left);
  var nx = ex + x - this.lastMouseX;
  var ny = ey + y - this.lastMouseY;
  this.div.style.left	= nx + 'px';
  this.div.style.top	= ny + 'px';
  this.lastMouseX	= ex;
  this.lastMouseY	= ey;
  this.onDrag(nx, ny);
  if (e.preventDefault) e.preventDefault();
  return false;
};

Drag.prototype.end = function()
{
  removeEventHandler( document, 'mousemove', this.documentMove );
  removeEventHandler( document, 'mouseup', this.documentStop );
  var time = (new Date()) - this.started;
  var x = parseInt(this.div.style.left),  dx = x - this.startX;
  var y = parseInt(this.div.style.top), dy = y - this.startY;
  this.onDragEnd( x, y, dx, dy, time );
  if( (dx*dx + dy*dy) < (4*4) && time < 1e3 )
    this.onClick( x, y, dx, dy, time );
};

function removeEventHandler( target, eventName, eventHandler )
{
  if( target.addEventListener )
    target.removeEventListener( eventName, eventHandler, true );
  else if( target.attachEvent )
    target.detachEvent( 'on' + eventName, eventHandler );
}

function addEventHandler( target, eventName, eventHandler, scope )
{
  var f = scope ? function(){ eventHandler.apply( scope, arguments ); } : eventHandler;
  if( target.addEventListener )
    target.addEventListener( eventName, f, true );
  else if( target.attachEvent )
    target.attachEvent( 'on' + eventName, f );
  return f;
}

function dom_setStyle(elt, str) {
		elt.setAttribute("style", str);
		// for MSIE:
		if (elt.style.setAttribute) {
			elt.style.setAttribute("cssText", str, 0);
			// positioning for MSIE:
			if (elt.style.position == "fixed") {
				elt.style.position = "absolute";
			}
		}
	}


var mycontent = '<div id="squatter"><div id="didilytop"><a href="Javascript:var newwin=window.open(\'http://scrumdidilyumptio.us/didilies/new\', location.href, \'width=300, height=225, status=no, location=no, directories=no, menubar=no, resizable=yes, copyhistory=no\');" class="adddidily" style="color:#ebb36b; font-size:12px; font-family:Verdana, Arial, Helvetica, sans-serif; text-decoration:none;"><img class="didilyimg"  src="%2FY7MZ3el2fKvx%2B26eeyVteuza9Hg8pPLZ5C14Iev3aLC5Wyk2nOi3Oqza%2F%2F%2B%2FnCj2ey1bpmezYnOZ%2Byco%2Byza%2ByUt%2B6VtO2cunKj2fGVtH2vuXKg4X%2Bi1nKg3uyXsOyjkf3z94zNZ9bsxozCgeu1Zeu1Z%2Fz%2B%2B5XOX%2B325YS4npTNY%2FOxa5HMZ5bMa%2FaUsvCpw7ebxNq3a9SYu%2FGya5vJaPGUs2%2Bk2vnq1v78%2BfbN3OusfcS%2Bar3Ngey3dOHr92al3PTA0%2FjjyP73%2Bcrc8Hamz%2F%2F9%2FavH58Pa4eukj%2Fnc59vuzZbPWqTTf%2Fr8%2Fv348fnRqa%2FEaG6j2u%2B0Y3Kf4IvBheyTu%2ByXtuiWtuuUtaHSe5LMZLLak%2Fnf6HSj2P%2F%2F%2F%2F327oOh1Ouybr7U7X2p2%2Fb5%2FJm84qzI6Ozz%2BrXO6trm9ePt98fa75PLaHSj1%2B6ya%2Fn7%2FfmTspTLZ%2Bu0avCqxOyTup3Qdfb5%2FeyUuHGf5fWwa5XNYf74%2BtLd75LKavbevyH5BAEAAF8ALAAAAAAQAA8AAAfEgF%2BCgg8PAACFg4pfD05EaTAwAzpDD4sPPwpSEi9ZnhhdloQ%2FAlIQHVgXBQWeSqJOChBeXjczNqusVyGMB1KzXgwxL7gWdUGFC7KzDBI2dVYFHxRJjQmyDR4cHdJJOwYlETlOCVRuRRsqJDJTJSYGBj45D0dVJFtMTCI8LO8GDgRGvoxgsgKBwQBRaPQrAcXSCS1bDCJoUcNBhXcRngxK4SKiwRYyaDhwIETRgxQQt2yZsM8HDlGDHpwYwaVJkx5%2F5A0KBAA7" border="0"> Add a Didily</a></div>';

var didilyxmlurl = 'http://scrumdidilyumptio.us/search/uris.xml?terms=';
var passurl = new String(window.location);
var startfrom = passurl.indexOf('//') + 2;
var urllen = passurl.length
var culllen = urllen - startfrom;
if(passurl[urllen-1]=='/')
	culllen--;
passurl = encodeURIComponent(passurl.substr(startfrom, culllen));

// GM_log('Search Query Encoded = ' + passurl);

GM_xmlhttpRequest({
    method: 'GET',
    url: didilyxmlurl + passurl,
    headers: {
        'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',
    },
    onload: function(responseDetails) {
        var parser = new DOMParser();
        var dom = parser.parseFromString(responseDetails.responseText, "application/xml");
        var didilies = dom.getElementsByTagName('didily');
        var title;
				//GM_log('didilies.length = ' + didilies.length);
				if(didilies.length >= 1)
				{
				mycontent += '<ul class="didilyul" style="list-style-type: none !important;">';
        for (var i = 0; i < didilies.length; i++) {
            from_title = didilies[i].getElementsByTagName('from_title')[0].textContent;
						//GM_log('from_title = ' + from_title);
            from_uri = didilies[i].getElementsByTagName('from_uri')[0].textContent;
						//GM_log('from_uri = ' + from_uri);
            relation = didilies[i].getElementsByTagName('relation')[0].textContent;
						//GM_log('relation = ' + relation);
            to_title = didilies[i].getElementsByTagName('to_title')[0].textContent;
						//GM_log('to_title = ' + to_title);
            to_uri = didilies[i].getElementsByTagName('to_uri')[0].textContent;
						//GM_log('to_uri = ' + to_uri);
            didily_link = didilies[i].getElementsByTagName('didily_link')[0].textContent;
						// GM_log('didily_link = ' + didily_link);
						mycontent += '<li class="didilyli"><a href="' + from_uri + '" style="color:#3987DC !important; font-size:12px !important; font-family:Verdana, Arial, Helvetica, sans-serif !important; margin-left:3px !important; text-decoration:none !important; list-style-type: none !important;" class="didilya">' + from_title + '</a> ';
						mycontent += '<a href="http://scrumdidilyumptio.us' + didily_link + '" style="color:#EA3D65 !important; font-style: italic !important; font-size:12px !important; font-family:Verdana, Arial, Helvetica, sans-serif !important; text-decoration:none !important; list-style-type: none !important;" class="didilya">' + relation + '</a> ';
						mycontent += '<a href="' + to_uri + '" style="color:#729c50 !important; font-size:12px !important; font-family:Verdana, Arial, Helvetica, sans-serif !important; text-decoration:none !important; list-style-type: none !important;" class="didilya">' + to_title + '</a></li>';
						//GM_log('mycontent = ' + mycontent);
						
        }
				
				mycontent += '</ul>';
				}
				/* This section removed because the customer doesn't want it to say anything if no didilies.
				else
				{
					mycontent += '<span style="color:#EA3D65; font-size:12px; font-family:Verdana, Arial, Helvetica, sans-serif; margin-left:5px;">Darn! No Didilies Dude.</span>';
				}
				*/
				mycontent += '</div>';
var body = document.getElementsByTagName('body')[0];
if(body) {
	var didilysquat = document.createElement('div');
	didilysquat.innerHTML = mycontent;
	//GM_log('mycontent = ' + mycontent);
	body.parentNode.insertBefore(didilysquat, body.nextSibling);
	
	var squatterWidth= 250;
	var addScrollWidth;
	if (document.documentElement.scrollHeight > document.documentElement.clientHeight)
		{var addScrollWidth = 20;}
	else
		{var addScrollWidth = 5;}
	
	var rightAligned = window.innerWidth - squatterWidth - addScrollWidth;
	
	//GM_log('document.documentElement.scrollHeight' + document.documentElement.scrollHeight);
	//GM_log('document.documentElement.clientHeight' + document.documentElement.clientHeight);
	//GM_log('rightAligned == ' + rightAligned);
	//GM_log('window.innerWidth == ' + window.innerWidth);
	//GM_log('addScrollWidth == ' + addScrollWidth);
	
	var didilytop = document.getElementById('didilytop');
	didilysquat.setAttribute("style", 'margin:0 0 0 0; border:1px solid #000000; width:'+squatterWidth+'px; position:fixed; left:'+rightAligned+'px; top:0px; background-color:#FFFFFF;z-index:999;');
	didilysquat.drag = new Drag(didilytop, didilysquat);
	var close = window.document.createElement("div");
		dom_setStyle(close,
"margin:0px 3px;position:absolute;top:3px;right:3px;width:10px;height:10px;border:1px solid #fff;line-height:8px;text-align:center;cursor:pointer;color:#3987DC;font-size:15px; background-color:#fff; font-weight:bold;z-index:999;");
		close.setAttribute("title","Click to close panel");
		close.addEventListener('click', function() { this.parentNode.style.display = "none"; }, true);
		close.appendChild(window.document.createTextNode("x"));
		didilysquat.appendChild(close);
															 
}		
    }
});

}



// Using gm_setvalue isn't great becuase it remembers the last location of any tab,
// would be better to use window.opener.location.href, but it isn't working. :(


if(window.opener)
{

var checkerdiv = document.getElementById('didily-squat-key');
if(checkerdiv)
{//this is indeed a didily page, remove header and footer

	var theheader = document.getElementById('header');
	if (theheader) {
    theheader.parentNode.removeChild(theheader);
}

var thefooter = document.getElementById('footer');
	if (thefooter) {
    thefooter.parentNode.removeChild(thefooter);
}

}//stop checking to see if this is indeed a didily page

var thefrombox = document.getElementById('didily_from_uri');
if (thefrombox)
{
	thefrombox.value = window.name;
}


var notice = document.getElementById('notice');
if(notice)
{
	if(notice.innerHTML.search(/successfully/)!= -1)
	{
		self.close();
	}
	
	else if (notice.innerHTML.search(/Please sign in/i) != -1)
	{
		top.outerWidth = 515;
		top.outerHeight = 300;
	}
	
	else if (notice.innerHTML.search(/Login successful/i) != -1)
	{
		top.outerWidth = 310;
		top.outerHeight = 280;
	}
	
}


}// stop checking to see if domain checks out. 300 / 225